package com.xipu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xipu.yygh.oss.config.properties.OssProperties;
import com.xipu.yygh.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * description: 文件上传实现类
 * @author: gql
 * @date: 2022/05
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        // 1.获取上传需要的几个值
        String endpoint = OssProperties.END_POINT;
        String accessKeyId = OssProperties.ACCESS_KEY_ID;
        String accessKeySecret = OssProperties.ACCESS_KEY_SECRET;
        String bucketName = OssProperties.BUCKET_NAME;
        try {
            // 2.创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 3.获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            // 3.1获取文件名
            String fileName = file.getOriginalFilename();
            // 3.2文件名添加随机值
            fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName;
            // 3.3文件名按日期创建文件夹分类
            String dateUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = dateUrl + "/" + fileName;

            // 4.上传方法(bucketName、上传文件的路径和名称、上传文件输入流)
            ossClient.putObject(bucketName, fileName, inputStream);

            // 5.关闭OSSClient
            ossClient.shutdown();

            // 6.上传文件在阿里云的路径
            // https://bishe-hospitals.oss-cn-beijing.aliyuncs.com/2022/04/07/8900e277c9964e858fd58aeb1cc07808image.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
